package com.example.aussiehealthhelper;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class HealthNotesAdapter extends RecyclerView.Adapter<HealthNotesAdapter.ViewHolder> {

    private final List<HealthNote> notes;
    private final OnNoteClickListener noteClickListener;

    public interface OnNoteClickListener {
        void onNoteClick(HealthNote note);
    }

    public HealthNotesAdapter(List<HealthNote> notes, OnNoteClickListener noteClickListener) {
        this.notes = notes;
        this.noteClickListener = noteClickListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_health_note, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        HealthNote note = notes.get(position);

        holder.tvTitle.setText(note.getTitle());
        holder.tvDate.setText(note.getCreatedAt());

        //内容预览
        String preview = note.getContent();
        if (preview.length() > 50) {
            preview = preview.substring(0, 47) + "...";
        }
        holder.tvPreview.setText(preview);

        holder.itemView.setOnClickListener(v -> noteClickListener.onNoteClick(note));
    }

    @Override
    public int getItemCount() {
        return notes.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle, tvDate, tvPreview;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvNoteTitle);
            tvDate = itemView.findViewById(R.id.tvNoteDate);
            tvPreview = itemView.findViewById(R.id.tvNotePreview);
        }
    }
}